package exp5;

//---------------------------------------------------------------
//  SocketServer_2.java   Author: 唐才铭   Date：2018-06-13
//
//  基于Java Socket实现服务器功能，传输方式用TCP
//  接收到后缀表达式，调用MyDC.java的功能计算后缀表达式的值，
//  把结果发送给客户端。
//---------------------------------------------------------------
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Stack;
import java.util.regex.Pattern;

/**
 * Created by tcm on 2018/6/13.
 */
public class SocketServer_2 {
    public static void main(String[] args) throws IOException {
        //1.建立一个服务器Socket(ServerSocket)绑定指定端口
        ServerSocket serverSocket=new ServerSocket(8800);
        //2.使用accept()方法阻止等待监听，获得新连接
        Socket socket=serverSocket.accept();
        //3.获得输入流
        InputStream inputStream=socket.getInputStream();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
        //获得输出流
        OutputStream outputStream=socket.getOutputStream();
        PrintWriter printWriter=new PrintWriter(outputStream);
        //4.读取用户输入信息
        String info=null;
        if (!((info = bufferedReader.readLine()) ==null)){
            System.out.println("我是服务器，用户信息为：" + info);
        }

        //服务器接收到后缀表达式，调用MyDC.java的功能计算后缀表达式的值，把结果发送给客户端
        String reply = MyDC.suffixToArithmetic(info);

        printWriter.write(reply);
        printWriter.flush();
        //5.关闭资源
        printWriter.close();
        outputStream.close();
        bufferedReader.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}